<template>
  <div class="work-order-list">
    <h2>工单列表</h2>
    
    <!-- 工单类型选择 -->
    <el-card class="search-card">
      <el-select v-model="selectedWorkOrderType" placeholder="请选择工单类型" @change="handleTypeChange">
        <el-option label="报告单" value="report"></el-option>
        <el-option label="修理工单" value="repair"></el-option>
        <el-option label="维护工单" value="maintenance"></el-option>
        <el-option label="执勤工单" value="duty"></el-option>
      </el-select>
    </el-card>

    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item v-if="selectedWorkOrderType === 'repair'" label="状态">
          <div style="display: flex; align-items: center;">
            <el-select v-model="searchForm.status" placeholder="请选择状态" style="flex: 1;">
              <el-option label="全部" value=""></el-option>
              <el-option label="待派发" value="待派发"></el-option>
              <el-option label="待受理" value="待受理"></el-option>
              <el-option label="已受理" value="已受理"></el-option>
              <el-option label="待归档" value="待归档"></el-option>
              <el-option label="已结束" value="已结束"></el-option>
            </el-select>
            <el-tag v-if="searchForm.status" type="info" style="margin-left: 10px;">
              {{ searchForm.status }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item v-if="selectedWorkOrderType === 'repair'" label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入工单标题（支持模糊）"></el-input>
        </el-form-item>
        <el-form-item v-if="selectedWorkOrderType === 'repair'" label="编号">
          <el-input v-model="searchForm.id" placeholder="请输入工单编号（支持模糊）"></el-input>
        </el-form-item>
        <el-form-item v-if="selectedWorkOrderType === 'repair'" label="相关设备">
          <el-input v-model="searchForm.device" placeholder="请输入相关设备（支持模糊）"></el-input>
        </el-form-item>
        <el-form-item v-if="selectedWorkOrderType === 'repair'" label="负责人">
          <el-input v-model="searchForm.assignee" placeholder="请输入负责人"></el-input>
        </el-form-item>
        <el-form-item v-if="selectedWorkOrderType === 'repair'" label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 动态表格 -->
    <component :is="currentTableComponent" :data="currentTableData"></component>

    <!-- 分页组件 -->
    <el-pagination
      v-if="showPagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right"
    ></el-pagination>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import ReportOrderTable from '@/components/ReportOrderTable.vue';
import RepairOrderTable from '@/components/RepairOrderTable.vue';
import MaintenanceOrderTable from '@/components/MaintenanceOrderTable.vue';
import DutyOrderTable from '@/components/DutyOrderTable.vue';

// 从后端获取修理工单数据
const fetchRepairWorkOrders = async () => {
  try {
    const response = await axios.get('/api/repair-work-orders');
    repairOrders.value = response.data;
    total.value = response.data.length;
  } catch (error) {
    console.error('Error fetching repair work orders:', error);
  }
};

// 当组件加载时获取数据
onMounted(() => {
  fetchRepairWorkOrders();
});

// 模拟数据
const reportOrders = ref([
  { id: 'R-001', title: '设备故障报告', type: '报告单', reporter: '张三', reportTime: '2023-10-01', description: '设备过热' },
  { id: 'R-002', title: '网络问题报告', type: '报告单', reporter: '李四', reportTime: '2023-10-02', description: '网络延迟高' },
  { id: 'R-003', title: '存储问题报告', type: '报告单', reporter: '王五', reportTime: '2023-10-03', description: '存储空间不足' },
  { id: 'R-004', title: '安全问题报告', type: '报告单', reporter: '赵六', reportTime: '2023-10-04', description: '安全漏洞' },
  { id: 'R-005', title: '应用问题报告', type: '报告单', reporter: '钱七', reportTime: '2023-10-05', description: '应用崩溃' }
]);

const repairOrders = ref([]);

const maintenanceOrders = ref([
  { id: 'WO-001', title: '服务器维护', type: '维护工单', assignee: '张三', status: '待派发', created_at: '2023-10-01', updated_at: '2023-10-02' },
  { id: 'WO-002', title: '网络设备维护', type: '维护工单', assignee: '李四', status: '待受理', created_at: '2023-10-03', updated_at: '2023-10-04' },
  { id: 'WO-003', title: '存储设备维护', type: '维护工单', assignee: '王五', status: '已受理', created_at: '2023-10-05', updated_at: '2023-10-06' },
  { id: 'WO-004', title: '应用维护', type: '维护工单', assignee: '赵六', status: '待归档', created_at: '2023-10-07', updated_at: '2023-10-08' },
  { id: 'WO-005', title: '安全维护', type: '维护工单', assignee: '钱七', status: '已结束', created_at: '2023-10-09', updated_at: '2023-10-10' }
]);

const dutyOrders = ref([
  { id: 'D-001', dutyPerson: '张三', dutyLocation: '机房A', dutyTime: '2023-10-01 08:00-17:00' },
  { id: 'D-002', dutyPerson: '李四', dutyLocation: '机房B', dutyTime: '2023-10-02 08:00-17:00' },
  { id: 'D-003', dutyPerson: '王五', dutyLocation: '机房A', dutyTime: '2023-10-03 08:00-17:00' },
  { id: 'D-004', dutyPerson: '赵六', dutyLocation: '机房B', dutyTime: '2023-10-04 08:00-17:00' },
  { id: 'D-005', dutyPerson: '钱七', dutyLocation: '机房A', dutyTime: '2023-10-05 08:00-17:00' }
]);

// 当前选择的工单类型
const selectedWorkOrderType = ref('repair');

// 当前显示的表格组件
const currentTableComponent = computed(() => {
  switch (selectedWorkOrderType.value) {
    case 'report':
      return ReportOrderTable;
    case 'repair':
      return RepairOrderTable;
    case 'maintenance':
      return MaintenanceOrderTable;
    case 'duty':
      return DutyOrderTable;
    default:
      return RepairOrderTable;
  }
});

// 当前表格的数据
const currentTableData = computed(() => {
  switch (selectedWorkOrderType.value) {
    case 'report':
      return reportOrders.value;
    case 'repair':
      return repairOrders.value;
    case 'maintenance':
      return maintenanceOrders.value;
    case 'duty':
      return dutyOrders.value;
    default:
      return repairOrders.value;
  }
});

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(5);

// 是否显示分页
const showPagination = ref(true);

// 查询表单数据
const searchForm = ref({
  id: '',
  title: '',
  status: '',
  device: '',
  assignee: '',
  dateRange: []
});

// 处理工单类型变化
const handleTypeChange = () => {
  currentPage.value = 1;
};

// 查询按钮点击事件，多条件查询
const handleSearch = async () => {
  try {
    const params = {
      id_like: searchForm.value.id,
      title_like: searchForm.value.title,
      status: searchForm.value.status,
      device_like: searchForm.value.device,
      assignee: searchForm.value.assignee,
      startDate: searchForm.value.dateRange ? searchForm.value.dateRange[0] : null,
      endDate: searchForm.value.dateRange ? searchForm.value.dateRange[1] : null
    };

    const response = await axios.get('/api/repair-work-orders/search', {
      params: params
    });

    repairOrders.value = response.data;
    total.value = response.data.length;
  } catch (error) {
    console.error('Error searching repair work orders:', error);
  }
};

// 重置按钮点击事件
const resetSearch = () => {
  searchForm.value = {
    id: '',
    title: '',
    status: '',
    device: '',
    assignee: '',
    dateRange: []
  };
  fetchRepairWorkOrders();
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};
</script>

<style scoped>
.work-order-list {
  padding: 0px; /* 减少页面顶部的空白 */
}

h2 {
  margin-top: 2px; /* 去掉标题上方的空白 */
  margin-bottom: 2px; /* 减少标题下方的空白 */
}

.search-card {
  margin-bottom: 2px; /* 减少卡片之间的空白 */
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.el-form-item {
  margin-bottom: 10px; /* 减少表单项之间的空白 */
}
</style>